<?php
	require_once ("../includes/config.php");
	if ($_SERVER["REQUEST_METHOD"] == "POST")
	{
		$error = 0;
		$fixed = 0;

		$from = $_POST['from'];
		//concatenate date with time
		$to = $_POST['to'];
		//concatenate date with time

		//compare out date of this contracts with upcoming contracts on the same
		// apartment
		$out_ts = strtotime($to);
		$in_ts = strtotime($from);

		//Contract Current Status
		$current_contract = query("SELECT contract_status FROM contracts WHERE contract_id = ?", $_POST['contract_id']);
		$contract_status = $current_contract[0]['contract_status'];
		$apartments = explode("|", $_POST['apartment_id']);
		foreach ($apartments as $apartment_id)
		{
			$contracts_p = query("SELECT * FROM contract_apartments where apartment_id = ? ", $apartment_id);

			foreach ($contracts_p as $contract_p)
			{
				$contract = query("SELECT * FROM contracts WHERE contract_id = ? and contract_id != ?", $contract_p['contract_id'], $_POST['contract_id']);
				if (!empty($contract))
				{
					$contract = $contract[0];

					if ($contract['contract_status'] == 3)
					{
						continue;
					}
					else
					{

						$contract_in_ts = strtotime($contract['mildai_from']);
						$contract_out_ts = strtotime($contract['miladi_out']);
						if ($contract_status == 2)
							$condition = 1;
						else
						if ($_POST['what-button'] == 2)
						{
							$apartment = query("SELECT status FROM apartments WHERE id = ?", $apartment_id);
							$condition = (($out_ts <= $contract_in_ts || $in_ts >= $contract_out_ts) && $apartment[0]['status'] != 1);
							//checks the dates and ensures that apartment is not red which indicates that
							// this apartment has clients in it
						}
						else//if booking is requested
						{
							$condition = ($out_ts <= $contract_in_ts || $in_ts >= $contract_out_ts);
						}
						if ($condition)
						{
							//KEEP Going
						}
						else
						{
							$error = 1;
							//indicates that there's a contract on the chosen apartment during this period
							//get $apartment name
							$apartment = query("SELECT apart_name FROM apartments WHERE id = ?", $apartment_id);
							$apartments_otherContracts .= $apartment[0]['apart_name'] . " ";
							break;
						}
					}
				}
			}

			//check if apartment in cleanning_ request state, if so display error and do not
			// show any action
			$apartment = query("SELECT status FROM apartments where id = ? ", $apartment_id);
			if ($apartment[0]['status'] == 8)
				$error = 2;
			//indicating that apartment is in cleanning_ request state

		}

		if ($error > 0)
		{
			if ($error == 1)
			{
				$_SESSION['error_message_pop'] = "فترة العقد المختارة غير مناسبة لوجود عقود فى نفس الفترة على الشقق " . $apartments_otherContracts;
				$_SESSION['recent_contract'] = $_POST['contract_id'];
				redirect("bookings.php");
			}
			else
			if ($error == 2)
			{
				$_SESSION['error_message_pop'] = "الشقق المختارة موجودة فى حالة طلب تنظيف، برجاء إنهاء الطلب قبل إجراء أى عمليات على العقد";
				$_SESSION['recent_contract'] = $_POST['contract_id'];
				redirect("bookings.php");
			}
		}
		else
		{
			if (isset($_POST['fixed_discount']))
				$fixed = $_POST['fixed_discount'];

			$amount = round($_POST['final-price'], 2);
			//make sure that no one can delete manager comment
			if ($_SESSION['r'] > 1)
			{
				//Get notes
				$contractNotes = query("SELECT * FROM contracts WHERE contract_id = ?", $_POST['contract_id']);
				$contractNotes = $contractNotes[0];
				$contractNotes = $contractNotes['notes'];
				if ($contractNotes == "")
				{
					//do nothing
					$notez = $_POST['notes'];
				}
				else
				{
					$notez = $contractNotes;
					if ($_POST['notes'] != "")//Notes aren't empty
					{
						//Filter the old comment and get the new one so we don't have duplicates.
						$newNotes = $_POST['notes'];
						$contractNotesLines = explode("\n", $contractNotes);
						foreach ($contractNotesLines as $contractNotesLine)
						{
							$contractNotesLine = trim($contractNotesLine);
							$newNotes = preg_replace("/$contractNotesLine/", '', $newNotes, 1);
						}
						$newNotes=preg_replace("/(^$([\r\n]|[\n])|^\s+)/m",'',$newNotes);
						//Decide if we need to add new line or not.
						$newLine = "\n";
						if(preg_match("/^(\r\n|\n)/",$newNotes))
						{
							$newLine="";
						}
						//Add the user name
						$newNotes="---------\n".$_SESSION['login_user'].":$newLine".$newNotes;
						$notez = $contractNotes . "\n" . $newNotes;
					}
				}
			}
			else
			{
				$notez = $_POST['notes'];
			}
			$result = query("UPDATE contracts SET notes = ?, period = ?, apartment_name=?, rent_type = ?,mildai_from = ? ,miladi_out = ? ,hijri_in = ? ,hijri_out = ? ,discount = ? ,
      chosen_weekly = ? ,chosen_daily = ? ,chosen_monthly = ?,total=?,fixed_discount=? where contract_id = ?", $notez, $_POST['period'], $_POST['apart_name'], $_POST['rent_type'], $from, $to, $_POST['hijri-from'], $_POST['hijri-to'], $_POST['discount'], $_POST['weekly_price'], $_POST['daily_price'], $_POST['monthly_price'], $amount, $fixed, $_POST['contract_id']);

			//update apartments in contract_apartments
			//DELETE all apartments related to this contract and then re-add them
			$query = query("DELETE FROM contract_apartments WHERE contract_id = ?", $_POST['contract_id']);

			if (!empty($_POST['what-button']))
			{
				if ($_POST['what-button'] == 2)
				{
					$status = 1;
					//update Contract Status
					$datee = date("Y-m-d h:i:s");
					$query = query("UPDATE contracts SET contract_status = 2,actual_in = ? WHERE contract_id = ?", $datee, $_POST['contract_id']);
					$_SESSION['success_message_pop'] = "تم حفظ العقد";
					$client = query('SELECT mobile,name from clients where id = ?', $_POST['client_id']);
					$name = $client[0]['name'];
					$mobile = $client[0]['mobile'];
					$message = "عزيزى /" . $name . "\n
              بقلوب تملئها المحبة نقول لكم اهلا وسهلا ومرحبا بكم في لؤلؤة ليمار (غرف واجنحة فندقية ) ونتمنى لكم اقامة سعيدة وان تنال خدماتنا رضائكم . دخولكم يوم " . $_POST['from'] . " وخروجكم يوم " . $_POST['to'] . " لمدة " . $_POST['period'] . " يوم. في حال طلب اي خدمة نأمل الاتصال بالاستقبال على التحويلة (صفر) او (100) علما بانه تتوفر خدمة الانترنت في جميع انحاء الفندق. نود لفت نظر سعادتكم بأن موعد الخروج Check Out المعتاد في الفندق هو الساعة الثانية ظهرا . رقم الفندق (920025725) ، فاكس: 6575959-012";
					$results = sendSMS($mobile, 'Lemar', utf8ToUnicode($message));

				}
				else
				if ($_POST['what-button'] == 1)
				{
					$status = 6;
					//update Contract Status
					$query = query("UPDATE contracts SET contract_status = 1 WHERE contract_id = ?", $_POST['contract_id']);
					$_SESSION['success_message_pop'] = "تم تعديل العقد بنجاح";

				}
				else
				if ($_POST['what-button'] == 3)
				{
					$status = 3;
					//update Contract Status
					$datee = date("Y-m-d h:i:s");
					$query = query("UPDATE contracts SET contract_status = 3,actual_ot = ? WHERE contract_id = ?", $datee, $_POST['contract_id']);
					$_SESSION['success_message_pop'] = "تم تصفية العقد وتحويل حالة الوحدة إلى نظافة";
					$_SESSION['recent_contract'] = $_POST['contract_id'];
					$client = query('SELECT mobile,name from clients where id = ?', $_POST['client_id']);
					$name = $client[0]['name'];
					$mobile = $client[0]['mobile'];
					$message = "عزيزى/ " . $name . "\n

  سعدنا بخدمتنا لكم ونتمنى ان تكونوا قضيتم معنا اوقات سعيدة وان تكون خدماتنا قد نالت رضائكم ونتطلع دائما لخدمتكم. للحجز مستقبلا نأمل الاتصال على الرقم الموحد للفندق (920025725) ،فاكس: 6575959-012.

  منسوبي لؤلؤة ليمار (غرف واجنحة فندقية)";
					$results = sendSMS($mobile, 'Lemar', utf8ToUnicode($message));
				}

				foreach ($apartments as $apartment)
				{
					$result = query("INSERT INTO contract_apartments 
				(contract_id,apartment_id) 
			VALUES 
				(?,?)", $_POST['contract_id'], $apartment);

					$currentApart = query("SELECT apart_name,status FROM apartments WHERE id=?", $apartment);
					$currentStatus = $currentApart[0]['status'];
					$currentname = $currentApart[0]['apart_name'];
					$datee = date("Y-m-d h:i:s");

					if ($status == 3)
					{

						//If there's bookings on this unit, set unit status to clean request
						$contracts = query("SELECT * from contract_apartments LEFT JOIN contracts on contract_apartments.contract_id  = contracts.contract_id WHERE apartment_id = ? and contract_status = 1 and contract_apartments.contract_id != ?", $apartment, $_POST['contract_id']);
						if (!empty($contracts))
						{
							//get Apartments Name
							$date = date('y-m-d');
							$time = date('g:ia');
							$sql = query("INSERT INTO requests (apart_status	,apart_name ,owner_id ,requset_type,time_beginning,date_beginning,time_ending,date_ending) VALUES (?,?,?,?,?,?,?,?)", 6, $currentname, $_SESSION['user_id'], 8, $time, $date, "", "");
							$update_status = query('UPDATE apartments SET status = ? WHERE id = ?', 8, $apartment);
							$updateHistoryTable = query("INSERT INTO history (action,date_happened) VALUE (?,?)", "Apartment {$currentname} changed from {$currentStatus} to 8", $datee);
						}
						else
						{
							$result = query("UPDATE apartments SET status=? where id=?", $status, $apartment);
							$updateHistoryTable = query("INSERT INTO history (action,date_happened) VALUE (?,?)", "Apartment {$currentname} changed from {$currentStatus} to {$status}", $datee);
						}
					}
					else
					{
						$result = query("UPDATE apartments SET status=? where id=?", $status, $apartment);
						$updateHistoryTable = query("INSERT INTO history (action,date_happened) VALUE (?,?)", "Apartment {$currentname} changed from {$currentStatus} to {$status}", $datee);
					}
				}
			}
			if ($_POST['sendRecentContrat'] > -1)
				$_SESSION['recent_contract'] = $_POST['sendRecentContrat'];

			$_SESSION['recent_contract'] = $_POST['contract_id'];

			if ($_POST['requsting-page'] == 1)
				redirect("apartments.php");
			else
				redirect("bookings.php");
		}
	}
?>